package cn.hyy.hrm.service.impl;

import cn.hyy.basic.util.PageList;
import cn.hyy.hrm.CourseESClient;
import cn.hyy.hrm.controller.vo.CourseVo;
import cn.hyy.hrm.doc.CourseDoucment;
import cn.hyy.hrm.doc.query.CourseDocumentQuery;
import cn.hyy.hrm.domain.Course;
import cn.hyy.hrm.domain.CourseDetail;
import cn.hyy.hrm.domain.CourseMarket;
import cn.hyy.hrm.domain.CourseResource;
import cn.hyy.hrm.mapper.*;
import cn.hyy.hrm.query.CourseQuery;
import cn.hyy.hrm.service.ICourseService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author hyy
 * @since 2020-04-02
 */
@Service
public class CourseServiceImpl extends ServiceImpl<CourseMapper, Course> implements ICourseService {
    @Autowired
    private CourseMapper courseMapper;

    @Autowired
    private CourseDetailMapper courseDetailMapper;

    @Autowired
    private CourseESClient courseESClient;

    @Autowired
    private CourseTypeMapper courseTypeMapper;

    @Autowired
    private CourseMarketMapper courseMarketMapper;

    @Autowired
    private CourseResourceMapper courseResourceMapper;


    /**
     * 前台用户检索上线了的课程
     * @param courseQuery
     * @return
     */
    @Override
    public PageList<CourseDoucment> searchOnline(CourseQuery courseQuery) {

        CourseDocumentQuery documentQuery = new CourseDocumentQuery();
        BeanUtils.copyProperties(courseQuery,documentQuery);
        PageList<CourseDoucment> doucmentPageList = courseESClient.search(documentQuery);

        return doucmentPageList;
    }


    @Override
    public PageList<Course> getByQuery(CourseQuery query) {
        IPage<Course> iPage = baseMapper.selectByQuery(new Page<>(query.getPage(),query.getRows()),query);
        PageList<Course> pageList = new PageList<>(iPage.getTotal(),iPage.getRecords());
        return pageList;
    }




    /**
     * 添加课程信息（基本信息+详情）
     * @param vo
     */
    @Override
    @Transactional
    public void add(CourseVo vo) {
        //向课程信息表中添加数据
        Course course = new Course();
        BeanUtils.copyProperties(vo,course);
        //初始化数据，进行数据冗余操作
        //冗余等级名称
//        Systemdictionaryitem grade = systemDictionaryitemClient.get(course.getGrade());
//        course.setGradeName(grade.getName());//等级名称，查询数据字典
        //冗余创建用户和租户 - 获取当前登录人的信息，先直接写死
        course.setUserId(42L);
        course.setUserName("hyy");
        course.setTenantId(26L);
        course.setTenantName("源码时代");

        course.setStatus(0);//默认状态为0，下线
        baseMapper.insert(course);

        //向课程详情表中添加数据
        CourseDetail courseDetail = new CourseDetail();
        BeanUtils.copyProperties(vo,courseDetail);
        courseDetail.setCourseId(course.getId());
        courseDetailMapper.insert(courseDetail);
    }

    /**
     * 修改2表数据
     * @param vo
     */
    @Override
    public void update(CourseVo vo) {
        //向课程信息表中添加数据
        Course course = new Course();
        BeanUtils.copyProperties(vo,course);

        course.setUserId(42L);
        course.setUserName("hyy");
        course.setTenantId(26L);
        course.setTenantName("源码时代");
        course.setStatus(0);//默认状态为0，下线
        baseMapper.updateById(course);
        //向课程详情表中添加数据
        CourseDetail courseDetail = new CourseDetail();
        BeanUtils.copyProperties(vo,courseDetail);
        CourseDetail courseId = courseDetail.setCourseId(course.getId());
        courseDetailMapper.update(courseId);
    }

    /**
     * 重写save方法
     *
     * 要向两张表中添加数据
     *      课程的基本信息表
     *      课程的详情表
     *
     * @param entity
     * @return
     */
    @Override
    public boolean save(Course entity) {
        return false;
    }

    /**
     * 删除2表数据
     * @param id
     * @return
     */
    @Override
    @Transactional
    public boolean removeById(Serializable id) {

        Course Courseby = courseMapper.selectById(id);
        baseMapper.deleteById(Courseby);

        CourseDetail courseDetail = new CourseDetail();
        BeanUtils.copyProperties(Courseby,courseDetail);
        CourseDetail courseId = courseDetail.setCourseId(Courseby.getId());
        Long id1 = courseId.getId();

        courseDetailMapper.delete(id1);

        return false;
    }


        /**
         * 课程上线
         * @param ids
         */
        @Override
        public void onLine(List<Long> ids) {
            //查询课程信息
           /* List<Course> courses = baseMapper.selectBatchIds(ids);
            //转为文档
            List<CourseDoucment> doucments = courses2Docs(courses);
            //批量保存
            courseESClient.saveBathc(doucments);*/

            //修改数据库的上线时间
            baseMapper.onLine(System.currentTimeMillis(),ids);

            //查询需要上线的课程信息
            List<Course> courses = baseMapper.selectBatchIds(ids);

            //调用es服务的接口进行上线操作
            courseESClient.saveBathc(courses2Docs(courses));
        }
    /**
     * 课程下线
     * @param ids
     */
    @Override
    @Transactional
    public void offLine(List<Long> ids) {
        //修改数据库的下线时间
        baseMapper.offLine(System.currentTimeMillis(),ids);
        //删除es
        courseESClient.delete(ids);
    }

    /**
     * 课程集合的转换
     * @param courses
     * @return
     */
    private List<CourseDoucment> courses2Docs(List<Course> courses) {
        List<CourseDoucment> docs = new ArrayList<>();
        CourseDoucment doc = null;
        for (Course course : courses) {
            doc = course2Doc(course);
            docs.add(doc);
        }
        return docs;
    }

    /**
     * 课程对象的转换
     * @param course
     * @return
     */
    private CourseDoucment course2Doc(Course course) {
        CourseDoucment doc = new CourseDoucment();
        doc.setId(course.getId());
        doc.setTypeId(course.getCourseTypeId());
        //all = 课程名称 课程类型名称 机构名称
        String courseName = course.getName();
        String courseTypeName = courseTypeMapper.selectById(course.getCourseTypeId()).getName();
        String tenantName = course.getTenantName();
        String all = courseName+" "+courseTypeName+" "+tenantName;
        doc.setAll(all);
        //charge
        //  CourseMarket    CourseResource   CourseDetail 可能为空，因为你可能还没有维护这三张表中的数据
        CourseMarket courseMarket =
                courseMarketMapper.selectOne(new QueryWrapper<CourseMarket>().eq("course_id", course.getId()));
        doc.setCharge(courseMarket!=null?courseMarket.getCharge():-1);
        doc.setGrade(course.getGrade());
        doc.setName(course.getName());
        CourseResource courseResource =
                courseResourceMapper.selectOne(new QueryWrapper<CourseResource>().eq("course_id", course.getId()));
        doc.setResources(courseResource!=null?courseResource.getResources():"");
        doc.setPrice(courseMarket!=null?courseMarket.getPrice():0);
        CourseDetail courseDetail =
                courseDetailMapper.selectOne(new QueryWrapper<CourseDetail>().eq("course_id", course.getId()));
        doc.setDescription(courseDetail!=null?courseDetail.getDescription():"");
        doc.setIntro(courseDetail!=null?courseDetail.getIntro():"");
        doc.setQq(courseMarket!=null?courseMarket.getQq():"");
        doc.setStartTime(course.getStartTime());
        return doc;
    }

}
